package com.lzc.lblog.lblog.schedules;


import com.lzc.lblog.lblog.entity.MPost;
import com.lzc.lblog.lblog.service.MPostService;
import com.lzc.lblog.lblog.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class ViewCountSyncTask {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MPostService postService;
    /**
     * 热议文章浏览数数据库同步
     */
    @Scheduled(cron="0 0/30 * * * ?")
    public void postViewCountSync(){
        //先获取所有的需要同步的文章
        Set<String> keys = redisTemplate.keys("post:*");
        if(keys.isEmpty()) return;
        List<MPost> mPosts = keys.stream().map(key -> {
            MPost post = (MPost) redisUtil.get(key);
            return post;
        }).collect(Collectors.toList());
        if (mPosts.isEmpty()&&mPosts.size()==0) return;
        mPosts.stream().forEach(post->{
            MPost byId = postService.getById(post.getId());
            if(post.getViewCount()!=byId.getViewCount()){
                byId.setViewCount(post.getViewCount());
                boolean b = postService.updateById(byId);
                System.out.println(b?"热议文章浏览数数据库同步成功------------------":"热议文章浏览数数据库同步失败---------------------");
            }
        });
    }

}
